import serial  # python串口库
import serial.tools.list_ports


class Comcontrol(serial.Serial):  # 定义串口控制类,继承串口类
    def __init__(self, port, baudrate, bytesize, stopbits, timeout, parity):  # 实例初始化
        super(Comcontrol, self).__init__()
        self.port = port
        self.baudrate = baudrate
        self.bytesize = bytesize
        self.stopbits = stopbits
        self.timeout = timeout
        self.parity = parity
        """建立串口连接"""
        """设置串口参数：串口号，波特率，数据长度，停止位,延迟时间，校验位"""
        self.com = serial.Serial(port=self.port,
                                 baudrate=self.baudrate,
                                 bytesize=self.bytesize,
                                 stopbits=self.stopbits,
                                 timeout=self.timeout,
                                 parity=self.parity)


def light_com_connect():           # 连接激光串口
    flag1 = False
    while flag1 is False:  # 没连接到激光模块串口则一直连接
        port_list = list(serial.tools.list_ports.comports())  # 搜索可用串口
        if len(port_list) == 0:  # 没有可用串口
            print("no useful COM\r\n")
        else:
            print("find com successful\r\n")
            for i in range(0, len(port_list)):
                port = port_list[i]  # 提取使用串口字符串
                port = str(port)
                print("you use: ", port[0:5], "\r\n")
                if port[0:5] == light_com_name:
                    light_ser = Comcontrol(port=light_com_name,  # 激光串口实例化
                                           baudrate=19200,
                                           bytesize=8,
                                           stopbits=1,
                                           timeout=0.6,
                                           parity='N')
                    flag1 = light_ser.com.is_open  # 激光模块是否打开标志
                    if flag1:
                        print("light connection success\r\n")
                        return light_ser
                else:
                    print("connection failed\r\n")


if __name__ == '__main__':
    light_ser_try = light_com_connect()

ser.close()
